package com.ngmaster.socket;


import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;


public class TcpClient {
	
	/**
	 * 线程函数
	 */
	protected Thread thread = null;
	
	/**
	 * 远程Ip
	 */
	protected String remoteIp = "127.0.0.1";
	
	/**
	 * 端口
	 */
	protected int remotePort = 10000;
	
	/**
	 * 客户端连接
	 */
	private ChannelFuture clientFuture = null;

	private ChannelHandlerContext ctx = null;
	
	/**
	 * 连接状态
	 */
	private ConnectState connectState = ConnectState.DisConnect;

	/**
	 * 初始化
	 * @param ip
	 * @param port
	 */
	public void init(String ip, int port) {
		remoteIp = ip;
		remotePort = port;
		connect();
	}

	/**
	 * 连接
	 */
	public void connect() {
		connectState = ConnectState.Connecting;
		thread = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					start();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		thread.start();
	}

	/**
	 * 启动
	 * @throws Exception
	 */
	private void start() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        try {
        	Bootstrap b = new Bootstrap();
            b.group(bossGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new TcpChannel(new ITcpLogic() {

                    	@Override
						public void Inactive(ChannelHandlerContext ctx) {
							inactiveConnected(ctx);
						}

						@Override
						public void Active(ChannelHandlerContext ctx) {
							activeConnected(ctx);
						}

						@Override
						public void Receive(ChannelHandlerContext ctx, ByteBuf data) {
							receiveData(ctx, data);
						}
					}));

            clientFuture = b.connect(remoteIp, remotePort).sync();
            clientFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            clientFuture = null;
            connectState = ConnectState.DisConnect;
        }
    }

    /**
     * 激活一个连接
     * @param ctx
     */
    private void activeConnected(ChannelHandlerContext ctx) {
    	this.ctx = ctx;
    	connectState = ConnectState.Connected;
	}

    /**
     * 失效一个连接
     * @param ctx
     */
    private void inactiveConnected(ChannelHandlerContext ctx) {
    	connectState = ConnectState.DisConnect;
	}
    
    /**
     * 接收到数据
     */
    private void receiveData(ChannelHandlerContext ctx, ByteBuf data) {
		if (ctx == null || data == null) {
			return;
		}
		System.out.println("receiveData:" + ctx);
	}
    
    /**
     * 连接状态
     * @return
     */
    public ConnectState getConnectState() {
    	return connectState;
    }



	/**
	 * 发送消息
	 * */
	public void sendMessage(ProtocolMessage protocolMessage) {
		ByteBuf out = this.ctx.alloc().buffer();
		out.writeBytes(protocolMessage.getByteArray().getBytes(), 0, protocolMessage.getByteArray().getWritePos());
		System.out.println("1111");
		this.ctx.channel().writeAndFlush(out);
	}
}
